<template>
  <div class="table-mechanism">
    <vab-query-form>
      <vab-query-form-left-panel>
        <el-button icon="el-icon-plus" type="primary" @click="EditADD(0,'')" >
          添加护工
        </el-button>


      </vab-query-form-left-panel>
      <vab-query-form-right-panel>
        <el-form ref="formInline" :inline="true" :model="queryForm" class="demo-form-inline">
          <el-form-item prop="buildingName" >
            <el-input v-model="queryForm.name" placeholder="护工名称"></el-input>
          </el-form-item>

          <el-form-item  prop="institutionNumber">

          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="search()">条件查询</el-button>
          </el-form-item>
        </el-form>

      </vab-query-form-right-panel>
    </vab-query-form>

    <el-table
      ref="tableSort"
      v-loading="listLoading"
      :data="list"



    >

<!--      <el-table-column show-overflow-tooltip label="机构名称" width="200"  prop="institutionName">-->

<!--      </el-table-column>-->
      <el-table-column
        show-overflow-tooltip
        label="护工名称"
        prop="name"
      ></el-table-column>
      <el-table-column label="性别" prop="gender">
        <template slot-scope="scope">
          <span v-if="scope.row.gender==0">男</span>
          <span v-if="scope.row.gender==1">女</span>
        </template>
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        label="身份证"
        prop="cardNo"
      ></el-table-column>
      <el-table-column
        show-overflow-tooltip
        label="住址"
        prop="address"
      ></el-table-column>

      <el-table-column
        show-overflow-tooltip
        label="出生日期"
        prop="birth"
      ></el-table-column>
      <el-table-column
        show-overflow-tooltip
        label="联系方式"
        prop="contactNumber"
      ></el-table-column>


      <el-table-column  label="入职时间">
        <template slot-scope="scope">
            {{scope.row.entryTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}')}}
        </template>
      </el-table-column>



      <el-table-column
        show-overflow-tooltip
        label="操作"
        width="180px"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button type="text"  @click="EditADD(scope.row.id, scope.row)">修改 <i class="el-icon-edit"></i></el-button>
          <el-button type="text" @click="del(scope.row.id, scope.row)" >
            删除<i class="el-icon-delete"></i>
          </el-button>

        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :background="background"

      :current-page=queryForm.currPageNo
      :total="total"
      :page-size="queryForm.limit"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    ></el-pagination>
    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible"
      width="450px"
      destroy-on-close
    >

      <el-form ref="form" :model="form" :rules="rules" >

        <el-form-item label="机构名称"  prop="institutionNumber" v-if="!isdisabled" >
          <el-select   v-model="form.institutionNumber"   placeholder="机构名称"  style="width: 100%"   @change="change" >
            <el-option
              v-for="item in options"
              :key="item.institutionNumber"

              :label="item.institutionName"
              :value="item.institutionNumber">
            </el-option>

          </el-select>
          <span v-if="isdisabled">{{form.institutionName}}</span>
        </el-form-item>


        <el-row :gutter="20">
          <el-col :span="12">
        <el-form-item label="姓名" prop="name">
          <el-input v-model.trim="form.name" autocomplete="off"   style="width: 100%"></el-input>
        </el-form-item>
          </el-col>
          <el-col :span="12">
          <el-form-item label="性别" >
            <el-select   v-model="form.gender"   placeholder="机构名称"  style="width: 100%"  >
              <el-option
                v-for="item in radios"
                :key="item.value"
                :label="item.label"
                :value="item.value">

              </el-option>

            </el-select>
<!--            <template>-->
<!--              <el-radio v-model="radio" :label="0">男</el-radio>-->
<!--              <el-radio v-model="radio" :label="1">女</el-radio>-->
<!--            </template>-->
          </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="身份证" prop="cardNo">
              <el-input  v-model="form.cardNo"  onkeyup="this.value=this.value.replace(/[^\X0-9]/g, '')"  style="width: 100%" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
        <el-form-item label="出生日期" >
          <el-date-picker
            v-model="value1"
            type="date"
            style="width: 100%"
            value-format="yyyy-MM-dd"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
        <el-form-item label="联系方式" prop="contactNumber">
          <el-input v-model="form.contactNumber" autocomplete="off"  style="width: 100%"></el-input>
        </el-form-item>
          </el-col>
          <el-col :span="12">
        <el-form-item label="住址" prop="address">
          <el-input  v-model="form.address"   style="width: 100%"></el-input>
        </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
        <el-form-item label="学历" required>
          <el-select   v-model="form.educationLevel"   placeholder="学历"  style="width: 100%"  >
            <el-option
              v-for="item in educationLevels"
              :key="item.dcNo"

              :label="item.name"
              :value="item.dcNo">
            </el-option>

          </el-select>

        </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="毕业院校" >
              <!--          <el-input v-model.trim="form.graduateInstitutions" autocomplete="off"></el-input>-->
              <el-select
                allow-create
                clearable
                v-model="form.graduateInstitutions"
                style="width: 100%"
                filterable
                remote
                reserve-keyword
                placeholder="毕业院校"
                :remote-method="remoteMethod"
                :loading="loading">
                <el-option
                  v-for="item in graduateInstitutionss"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>

          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
        <el-form-item label="证书编号" >
          <el-input v-model.trim="form.certificateNumber" autocomplete="off" style="width: 100%"></el-input>
        </el-form-item>
          </el-col>
          <el-col :span="12">
        <el-form-item label="入职日期" required >
          <el-date-picker
            v-model="value2"
            type="date"
            style="width: 100%"
            value-format="yyyy-MM-dd"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="护工职位" required>
          <el-select   v-model="value3"   placeholder="护工职位" style="width: 100%;z-index: 9999">
            <el-option
              v-for="item in option"
              :key="item.dcNo"

              :label="item.name"
              :value="item.dcNo">
            </el-option>

          </el-select>

        </el-form-item>

          </el-col>


          <el-col :span="12">
        <el-form-item prop="inpNumber" label="分管病区" >
          <el-select   multiple  v-model="form.inpNumber"   placeholder="选择病区"  style="width: 100%;z-index: 9999" >
            <el-option

              v-for="item in inpNumbers"
              :key="item.inpNumber"

              :label="item.name"
              :value="item.inpNumber">
            </el-option>

          </el-select>
        </el-form-item>

          </el-col>
          <el-form-item label="账号类型"  required v-if="!isshow">
            <el-select v-model="type" placeholder="请选择"      style="width: 100%" @change="changetype">
              <el-option
                style="width: 100%"
                v-for="item in types"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item   required v-if="!type&&!isshow"
          >
            <el-select v-model="form.uname" placeholder="请选择"                 no-data-text="暂无账号可用"
                       style="width: 100%"
            >
              <el-option
                style="width: 100%"
                v-for="item in unames"
                :key="item.uname"
                :label="item.userName"
                :value="item.uname">
              </el-option>
            </el-select>
          </el-form-item>

          <el-row :gutter="20" v-if="type&&!isshow" >

            <el-col :span="12">

              <el-form-item label="用户名" prop="uname"  >
                <el-input v-model="form.uname" ></el-input>

              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="密码" prop="password" >
                <el-input v-model="form.password" ></el-input>

              </el-form-item>
            </el-col>
          </el-row>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="close" >取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
    import { add } from "@/api/staff";
    import  sites  from "@/api/sites";
    import { revise,findinpatient } from "@/api/staff";
    import { search } from "@/api/staff";
    import { del } from "@/api/staff";
    import { parseTime} from "@/utils/index";
    import { isIdentityId } from "@/api/validate"
    import {searchdoctor} from "../../api/doctor";

    export default {
        name: "Staff",
        filters:{
            parseTime:parseTime
        },

      data() {
          var checkIdentitytionId  = (rule, value, callback) => {
                  var errorMsg = isIdentityId(value);
                  if (errorMsg != "") {

                      callback(new Error(errorMsg));
                  }else {


                    this.getBirthdayFromIdCard(value)
                      callback();
                  }

              }
        return {

            rules: {
                institutionNumber: [
                    {required: true, message: '机构名称', trigger: 'change'},

                ],
                name: [
                    {required: true, message: '名称', trigger: 'blur'},

                ],
                inpNumber: [
                    {required: true, message: '分管病区', trigger: 'change'},

                ],
                contactNumber: [
                    {required: true, message: '联系方式', trigger: 'blur'},

                ],
                certificateNumber: [
                    {required: true, message: '证书编号', trigger: 'blur'},

                ],
                cardNo: [
                    {required: true, validator: checkIdentitytionId , trigger: "blur" }
                ],
                address: [
                    {required: true, message: '居住地址' , trigger: "blur" }
                ],

                uname: [
                    {required: true, message: '用户名' , trigger: "blur" }
                ],

                password: [
                    {required: true, message: '密码' , trigger: "blur" }
                ],

            },
            states:[
          '1'

            ],
            lists: [],
            inpNumbers:[],
            loading:false,
            title:"添加护工",
            isdisabled:false,
            options: "",
            option:"",
            value: '',
            value1:"",
            value2:"",
            value3:'',
            value4:"",
            dialogFormVisible: false,
            list: [],
            isshow:false,
            unames:[],
            radio: 0,
            radios:[
                {
                    value: 0,
                    label: '男'
                }, {
                    value: 1,
                    label: '女'
                }
            ],
            formInline:{

            },
            graduateInstitutionss:{

            },
            educationLevels:[],
          form:{

              certificateNumber:"",
              educationLevel:19,
              graduateInstitutions:"",
              institutionNumber:"",
              birth:"",
              entryTime:"",
              gender:0,
              name:"",
              office:"",
              contactNumber:"",
              cardNo:"",
              address:"",
              inpNumber:[],
              uname:"",
              password:"",
          },
            type:1,
            types:[
                {
                    value: 0,
                    label: '选择已有账号'

                },
                {
                    value: 1,
                    label: '创建新的账号'

                },
            ],
          listLoading: true,
          total: 0,
          background: true,
          selectRows: "",
          elementLoadingText: "正在加载...",
           id:0,
          queryForm: {
            currPageNo: 1,
            limit: 10,
            institutionNumber:"",
              name:"",
          },
        };
      },
        created(){
            for(var i=0;i<sites.sites.length;i++){

                for (var j=0;j<sites.sites[i].college[0].sites.length;j++){


                    this.states.push(sites.sites[i].college[0].sites[j].name)

                }
            }
            this.queryForm.institutionNumber=localStorage.getItem("institutionNumber")
            this.value3=JSON.parse(localStorage.getItem("dictionary"))
            for(var i=0;i<this.value3.length;i++){
                  console.log(this.value3[i])
                if(this.value3[i].mark=="workerOffice"){
                    this.option=(this.value3[i].childs)
                }else if (this.value3[i].mark == "educationLevel") {
                    this.educationLevels = (this.value3[i].childs)

                }
            }

            console.log(this.option)
            setTimeout(() => {
                this.options= JSON.parse(localStorage.getItem("childinstitutionNumber"));
            }, 1000);


            this.search()
            this.findinpatient()
        },
        mounted() {
            this.lists = this.states.map(item => {

                return { value: `${item}`, label: `${item}` };
            });
        },
        methods: {
          getBirthdayFromIdCard(idCard) {
            var birthday = "";
            if(idCard != null && idCard != ""){
              if(idCard.length == 15){
                birthday = "19"+idCard.substr(6,6);
              } else if(idCard.length == 18){
                birthday = idCard.substr(6,8);
              }

              birthday = birthday.replace(/(.{4})(.{2})/,"$1-$2-");
            }

            this.value1=birthday
          },
            findinpatient(){
                let institutionNumber=localStorage.getItem("institutionNumber")
                findinpatient({institutionNumber}).then(res => {
                    console.log(res)
                    this.inpNumbers=res.data


                })

            },
            EditADD(id,data) {
              this.id = id





                if(id>0){
                  this.isdisabled=true
                    this.isshow=true

                    this.title="编辑护工"

                  this.form={...data}

                   console.log(this.form)

                    this.form.inpNumber=data.inpNumbers

                this.value1=data.birth
                this.value2=data.entryTime
                this.value=data.institutionName
                this.value3=data.office

              }else {
                    this.isshow=false
                    this.isdisabled=false
                  this.form.certificateNumber=""
                  this.form.graduateInstitutions=""
                  this.form.educationLevel=19
                this.value=""
                this.value1=""
                this.value2=""
                this.value3=1
                    this.form.inpNumber=[]
                this.form.gender=0
                  this.form.institutionNumber=localStorage.getItem("institutionNumber")
                  this.form.birth=""
                    this.form.cardNo="",
                       this.form.address="",
                  this.form.entryTime=""
                  this.form.name=""
                  this.form.office=""
                  this.form.contactNumber=""
                // this.form={
                //   institutionNumber:"",
                //   birth:"",
                //   entryTime:"",
                //   gender:"",
                //   name:"",
                //   office:"",
                //   contactNumber:"",
                // }
              }

                this.dialogFormVisible = true;
            },
            remoteMethod(query) {
                if (query !== '') {
                    this.loading = true;
                    setTimeout(() => {
                        this.loading = false;
                        this.graduateInstitutionss = this.lists.filter(item => {
                            return item.label.toLowerCase()
                                .indexOf(query.toLowerCase()) > -1;
                        });
                    }, 200);
                } else {
                    this.options = [];
                }
            },
            change(value){
                this.form.institutionNumber=value

            },
            changes(value){
                this.queryForm.institutionNumber=value


            },
          search(id,data){
              this.listLoading = true;

            if(id==1){
              this.queryForm.currPageNo=1
            }else {

            }
             search(this.queryForm).then(res =>{
               console.log(res)
                 this.list=res.data.data
                 this.total=res.data.total


              setTimeout(() => {
                this.listLoading = false;
              }, 500);
            })

          },
            changetype(value){
                this.$set(this.form,'password','')
                this.$set(this.form,'uname','')
                if(value){
                    this.$set(this.form,'uname','')
                }else {
                    let organNumber=localStorage.getItem('institutionNumber')
                    searchdoctor({organNumber}).then(res =>{
                        console.log(res)
                        this.unames=res.data
                        if(res.data){
                            this.$set(this.form,'uname',res.data[0].uname)

                        }
                    })
                }
            },
            save() {
                // this.form.gender = this.radio
                this.form.birth = (this.value1)
                this.form.entryTime = (this.value2)
                this.form.office = this.value3
                console.log(this.form)
                this.$refs['form'].validate(async (valid) => {
                    if (valid) {
                        if(this.id>0){

                            const {code} = await revise(this.form);
                            if(code==200){
                                this.$message({

                                        message: "修改成功",
                                        type: 'success'
                                }

                                    );
                                this.dialogFormVisible=false
                                this.search();

                            }else {
                                return false
                            }
                        }else{
                            console.log(this.form)
                            const {code} = await add(this.form);
                            if(code==200){
                                this.$message({

                                        message: "添加成功",
                                        type: 'success'
                                    }

                                );
                                this.dialogFormVisible=false
                                this.search();

                            }else {
                                return false
                            }
                        }




                    }
                    else {
                        return false;
                    }
                });

            },
          del(index,row){
              console.log(row)
            let number=row.number

            this.$baseConfirm("你确定要删除当前项吗", null, async () => {
              const {code, msg } = await del(({number}));
              if(code==200){

                this.$baseMessage('删除成功', "success");
                this.search();
              }else {

              }
            });
          },
          handleSizeChange(val) {
            this.queryForm.limit = val;
            this.search();
          },
          handleCurrentChange(val) {

            this.queryForm.currPageNo = val;
            this.search();
          },
            close(){
                this.dialogFormVisible = false;
            },
        },
    }
</script>

<style scoped>

</style>
